package com.linwancun.lwcyback.controller;

import com.linwancun.lwcyback.model.*;
import com.linwancun.lwcyback.service.*;
import com.linwancun.lwcyback.util.JsonTransformation;
import com.linwancun.lwcyback.util.Token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.util.*;

@RestController
@EnableAutoConfiguration
/**
 *@类名 PatientController
 *@描述：患者控制器
 *@作者：高国彬
 *@日期 2019-07-19 11:54
 *@版本:1.0
 **/

public class PatientController {
    @Autowired(required = false)
    // patient的service对象
    private PatientServiceImp patientService;

    @Autowired(required = false)
    // 症状的service对象
    private SymptomaticServiceImp symptomaticServiceImp;

    @Autowired(required = false)
    // 医生的service对象
    private DoctorServiceImp doctorServiceImp;

    @Autowired(required = false)
    // 医院的service对象
    private HospitalServiceImpl hospitalServiceimp;

    @Autowired(required = false)
    // 健康评估的service对象
    private HealthAssessmentResultServiceImpl healthAssessmentResultService;

    @Autowired(required = false)
    // 话题的service对象
    private HuatiServiceImp huatiServiceImp;

    @Autowired(required = false)
    // 聊天记录的service对象
    private ChatRecordServiceImpl chatRecordServiceimp;

    @Autowired
    // 一个全局的请求对象
    private HttpServletRequest request;


    @GetMapping("/patient/checktoken")
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:54
     * @param
     * @return java.lang.String
     * @throws
     * @since
     */
    //  检查令牌是否有效
    public String checktoken() {
        try {
            // 获取令牌
            String jwt = (String) request.getHeader("token");

            // 从令牌中提取信息
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary("4234dfasdfqdd"))
                    .parseClaimsJws(jwt).getBody();

            // 新建查询对象
            Patient patient = new Patient();
            patient.setAccountnumber(claims.getId());

            // 获取查找到的患者
            Patient foundPatient = patientService.find(patient);

            // 判断患者是否为空以及token是否合法
            if (foundPatient == null && !claims.getSubject().equals("patient") && claims.getExpiration().before(new Date()))
                return "404";
            return JsonTransformation.objectToJson(foundPatient);
        } catch (Exception e) {
            return "404";
        }

    }


    @PostMapping("/patient/login")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:55
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */
    // 登录
    public String login(@RequestBody String str) {
        // 获取从前端传回的患者实例
        Patient patient = JsonTransformation.jsonToObject(str, Patient.class);
        Patient foundPatient = patientService.find(patient);

        // 创建token以返回给患者
        Token t = new Token();
        String jwt = t.createJWT(patient.getAccountnumber(), "lwcy", "patient", 60 * 60 * 24 * 3);

        // 新建返回给患者token的目标实例
        TokenCharactor tokenCharactor = JsonTransformation.jsonToObject(str, TokenCharactor.class);
        tokenCharactor.setPatient(foundPatient);
        tokenCharactor.setToken(jwt);

        // 如果查找到的患者为空则返回404
        if (foundPatient == null)
            return "404";
        return JsonTransformation.objectToJson(tokenCharactor);
    }

    @PostMapping("/patient/forgetpassword")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:55
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */
    // 忘记密码
    public String forgetpassword(@RequestBody String str) {
        // 获取传过来的患者的信息
        Patient patient = JsonTransformation.jsonToObject(str, Patient.class);

        try {
            // 构造一个新的患者对象做查询对象
            Patient newpatient = new Patient();
            newpatient.setAccountnumber(patient.getAccountnumber());

            // 从数据库获取是否有这个对象
            Patient referpatient = patientService.find(newpatient);

            //如果没有这个对象则返回404
            if (referpatient == null)
                return "404";
            referpatient.setPassword(patient.getPassword());
            patientService.save(referpatient);
            return "200";
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/updatepatientinfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:55
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String updatepatientinfo(@RequestBody String str) {
        // 从传过来Json中，转换成患者对象
        Patient patient = JsonTransformation.jsonToObject(str, Patient.class);
        try {
            // 保存成功则返回200 否则返回404
            patientService.save(patient);
            return "200";
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/insertpatient")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 12:07
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String insertpatient(@RequestBody String str) {
        Patient patient = JsonTransformation.jsonToObject(str, Patient.class);
        try {
            patientService.insert(patient);
            return "200";
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/getpatientinfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:55
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getpatientinfo(@RequestBody String str) {
        Patient patient = JsonTransformation.jsonToObject(str, Patient.class);
        try {
            return JsonTransformation.objectToJson(patientService.find(patient));
        } catch (Exception e) {
            return "404";
        }
    }

    @GetMapping("/patient/getSymptomaticlist")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getSymptomaticlist() {

        try {
            return JsonTransformation.listToJson(symptomaticServiceImp.getAll());
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/getSymptomatic")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getSymptomatic(@RequestBody String str) {
        Symptomatic symptomatic = JsonTransformation.jsonToObject(str, Symptomatic.class);
        try {
            return JsonTransformation.objectToJson(symptomaticServiceImp.find(symptomatic));
        } catch (Exception e) {
            return "404";
        }
    }

    @GetMapping("/patient/getdoctorinfolist")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getdoctorinfolist() {

        try {
            return JsonTransformation.listToJson(doctorServiceImp.getAll());
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/getdoctor")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getDoctor(@RequestBody String str) {
        Doctor doctor = JsonTransformation.jsonToObject(str, Doctor.class);
        try {
            return JsonTransformation.objectToJson(doctorServiceImp.find(doctor));
        } catch (Exception e) {
            return "404";
        }
    }

    @GetMapping("/patient/gethospitalinfolist")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param
     * @return java.lang.String
     * @throws
     * @since
     */

    public String gethospitalinfolist() {
        try {
            return JsonTransformation.listToJson(hospitalServiceimp.getAll());
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/gethospitalinfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String gethospitalinfo(@RequestBody String str) {

        Hospital hospital = JsonTransformation.jsonToObject(str, Hospital.class);
        try {
            return JsonTransformation.objectToJson(hospitalServiceimp.find(hospital));
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/getcheckresult")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getcheckresult(@RequestBody String str) {

        HealthassessmentResult healthassessmentResult = JsonTransformation.jsonToObject(str, HealthassessmentResult.class);
        try {
            return JsonTransformation.objectToJson(healthAssessmentResultService.find(healthassessmentResult));
        } catch (Exception e) {
            return "404";
        }
    }

    @GetMapping("/patient/getarticleinfoList")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getarticleinfoList() {
        try {
            return JsonTransformation.listToJson(huatiServiceImp.getAll());
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/getarticleInfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getarticleInfo(@RequestBody String str) {

        Huati huati = JsonTransformation.jsonToObject(str, Huati.class);
        try {
            return JsonTransformation.objectToJson(huatiServiceImp.find(huati));
        } catch (Exception e) {
            return "404";
        }
    }


    @PostMapping("/patient/getchatinfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:56
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getchatinfo(@RequestBody String str) {

        Chatrecord chatrecord = JsonTransformation.jsonToObject(str, Chatrecord.class);
        try {
            return JsonTransformation.listToJson(chatRecordServiceimp.getList(chatrecord));
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/getnewchat")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:57
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getnewchat(@RequestBody String str) {

        Chatrecord chatrecord = JsonTransformation.jsonToObject(str, Chatrecord.class);
        chatrecord.setIsread(0);
        try {
            return JsonTransformation.listToJson(chatRecordServiceimp.getNewRecord(chatrecord));
        } catch (Exception e) {
            return "404";
        }
    }


    @PostMapping("/patient/chat")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:57
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String chat(@RequestBody String str) {
        Chatrecord chatrecord = JsonTransformation.jsonToObject(str, Chatrecord.class);
        try {
            chatRecordServiceimp.insert(chatrecord);

            Chatrecord newchatrequest = new Chatrecord();
            newchatrequest.setPatientid(chatrecord.getPatientid());
            newchatrequest.setDoctorid(chatrecord.getDoctorid());
            return JsonTransformation.listToJson(chatRecordServiceimp.getList(newchatrequest));
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/patient/getchateddoctors")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:57
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getchateddoctors(@RequestBody String str) {


        try {
            Patient patient = JsonTransformation.jsonToObject(str, Patient.class);
            Chatrecord chatrecord = new Chatrecord();
            chatrecord.setPatientid(patient.getPatientid());
            List<Chatrecord> chatrecordList = chatRecordServiceimp.getList(chatrecord);
            Set<Integer> set = new HashSet<>();

            Iterator<Chatrecord> iterator = chatrecordList.iterator();
            List<Doctor> doctorList = new ArrayList<>();

            while (iterator.hasNext()) {
                Chatrecord chatrecord1 = iterator.next();
                if (set.contains(chatrecord1.getDoctorid())) {
                    continue;
                }
                set.add(chatrecord1.getDoctorid());
                Doctor doctor = new Doctor();
                doctor.setDoctorid(chatrecord1.getDoctorid());
                doctorList.add(doctorServiceImp.find(doctor));
            }
            return JsonTransformation.listToJson(doctorList);
        } catch (Exception e) {
            return "404";
        }
    }


    @GetMapping("/patient/test/{para}")
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:57
     * @param para
     * @param id
     * @param password
     * @return java.lang.String
     * @throws
     * @since
     */

    public String patientLogin(@PathVariable String para,
                               @RequestParam(value = "id", required = true) String id,
                               @RequestParam(value = "password", required = true) String password) {
        Patient patient = new Patient();
        patient.setPatientid(Integer.parseInt(id));
        patient.setPassword(password);

        Patient foundPatientt = patientService.find(patient);

        if (foundPatientt == null)
            return "404";
        return "200";
    }

    @PostMapping("/patient/why")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:57
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String returntest(@RequestBody String str) {
        System.out.println(str);
        Manager manager = JsonTransformation.jsonToObject(str, Manager.class);
//        Manager manager = new Manager();
        manager.setManageraccountnumber("asdasd");
        return JsonTransformation.objectToJson(manager);
    }

    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:57
     * @param null
     * @return
     * @throws
     * @since
     */

    public static void main(String[] args) {
        SpringApplication.run(PatientController.class, args);
    }

}